<template>
  <div>
    <div class="app_card mb-2 pt-4 pb-4">
      <div class="d-flex justify-content-between search-form">
        <div class="flex-grow-1">
          <el-select clearable v-model="queryForm.buildingId" placeholder="请选择大楼" class="w200px mr-3" autocomplete="off"
            @change="floorFetch">
            <el-option v-for="item in buildingStore.bildingList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
          <el-select clearable v-model="queryForm.floorId" placeholder="请选择楼层" class="w200px mr-3" autocomplete="off"
            @change="roomFetch">
            <el-option v-for="item in floorStore.floorList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
          <el-button type="primary" plain @click="onRefresh()">查询</el-button>
        </div>
        <div>
          <el-button type="primary" @click="updataK4">上传K4</el-button>
          <el-button type="primary" plain @click="selectFloor">按楼层更新K4</el-button>
          <el-button type="primary" plain @click="selectRoom">选择教室更新K4</el-button>
        </div>
      </div>
    </div>
    <div class="app_card pt-4  pb-5">
      <el-table v-loading="loading" element-loading-text="查询中..." stripe size="large" :data="dataOfTable"
        height="calc(100vh - 300px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="教室ID" prop="id" align="center" width="100">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="教室名称" prop="name" align="center" width="120">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="大楼" prop="building" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.building }}</template>
        </el-table-column>
        <el-table-column label="楼层" prop="floor" align="center" show-overflow-tooltip width="100">
          <template #default="scope">{{ scope.row.floor }}</template>
        </el-table-column>
        <el-table-column label="教室IP" prop="ip" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.ip }}</template>
        </el-table-column>
        <el-table-column label="PING时间" prop="lastPingTime" align="center" width="240" show-overflow-tooltip>
          <template #default="scope">
            <div class="t-l">
              <div>
                服务器时间：{{ scope.row.lastPingTime == 0 ? "-" : scope.row.lastPingTime }}
              </div>
              <div>
                中控时间：{{ scope.row.coreTime == 0 ? "-" : scope.row.coreTime }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="卡更新时间" prop="cardUpdateTime" align="center" width="240" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.cardUpdateTime == 0 ? "-" : scope.row.cardUpdateTime }}</template>
        </el-table-column>
        <el-table-column label="系统" prop="system" align="center" show-overflow-tooltip width="120">
          <template #default="scope">{{ scope.row.system }}</template>
        </el-table-column>
        <el-table-column label="K4版本号" prop="k4Version" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.k4Version }}</template>
        </el-table-column>
        <el-table-column label="更新K4" prop="k4MD5" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="success" link @click="upgradeK4(scope.row)" v-if="scope.row.lastK4MD5 !== scope.row.k4MD5 &&
              scope.row.lastK4MD5 != ''
              ">更新k4</el-button>
          </template>
        </el-table-column>
        <el-table-column label="更新bin" prop="binMD5" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="warning" link @click="upgradeBin(scope.row)" v-if="scope.row.lastBinMD5 !== scope.row.binMD5 &&
              scope.row.lastBinMD5 != ''
              ">更新bin</el-button>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="onUpdataBin(scope.row)">上传bin </el-button>
            <el-button link type="primary" @click="onDetailRow(scope.row)">详情</el-button>
          </template>
        </el-table-column>

      </el-table>
      <Pagination ref="paginationRef" @handleChange="handleChange" />

    </div>
    <DetailDialog ref="detailDialogRef" @success="loadData()"></DetailDialog>
    <UpdataBinDialog ref="updataBinDialogRef" @success="loadData()"></UpdataBinDialog>
    <UpdataK4Dialog ref="updataK4DialogRef" @success="loadData()"></UpdataK4Dialog>
  </div>
</template>
  
<script setup>
/**
 * 角色组件
 */
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
//组件
import Pagination from '@/components/pagination/index.vue';
import UpdataK4Dialog from './UpdataK4Dialog.vue';
import UpdataBinDialog from './UpdataBinDialog.vue';
import DetailDialog from './DetailDialog.vue';
import { roomTypeList } from '@/apis/model/RoomModel';
import { findValue } from '@/utils/EsCommon';
import { timestampToTime } from '@/utils/EsDate.js';

import useBuildingStore from '@/stores/useBuildingStore';
import useFloorStore from '@/stores/useFloorStore';

// ======================================================
//                      变量声明
// ======================================================
const buildingStore = useBuildingStore();
const floorStore = useFloorStore();


// ======================================================
//                      变量声明
// ======================================================
const loading = ref(false);

// 组件引用
const paginationRef = ref(null);
const updataBinDialogRef = ref(null);
const updataK4DialogRef = ref(null);
const detailDialogRef = ref(null);


// 表格数据
const roomTypeOption = ref(roomTypeList);
const dataOfTable = ref([]);

// 表格查询参数
const queryForm = ref({
  buildingId: "",
  floorId: "",
})
// 表格查询参数
const queryParam = ref({
  sort: "Id",
  order: "asc",
  page: 1,
  limit: 10,
  query: ""
})
// 表格多选数据
const multipleSelection = ref([]);

// ======================================================
//                      点击操作
// ======================================================


// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  paginationRef.value?.changeTotal({ totalCount: 0 })
  loadData();
}


// 选择教室更新K4
const selectFloor = () => {
  if (queryForm.value.floorId) {
    let selectName = floorStore.floorList.find(
      (val) => val.id == queryForm.value.floorId
    ).name;
    ElMessageBox.confirm(` 你已选择 ${selectName}所有教室，是否升级K4`, '提示').then(() => {
      EsAjax.post(ApiUrls.updateK4, {
        selectType: 1,
        list: [queryForm.value.floorId],
      }).then(res => {
        console.log(res)
        if (res.data.code != 200) {
          ElMessage.warning(res.data.data + res.data.msg);
          return;
        }
        ElMessage.success(res.data.msg);
        loadData();
      }).catch(err => {
        ElMessage.error('网络错误：' + err.message);
      })
    }).catch(() => { })
  } else {
    ElMessage.info("请选择楼层");

  }

}
// 处理表格全选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 选择教室更新K4
const selectRoom = () => {
  console.log(multipleSelection.value)
  let n = multipleSelection.value.length, ids = multipleSelection.value.map((item) => item.id);
  console.log("ids", ids)
  console.log("n", n)
  if (n) {
    ElMessageBox.confirm(` 你已选择 ${n}间教室，是否升级K4`, '提示').then(() => {
      EsAjax.post(ApiUrls.updateK4, {
        selectType: 2,
        list: ids,
      }).then(res => {
        console.log(res)
        if (res.data.code != 200) {
          ElMessage.warning(res.data.data + res.data.msg);

          return;
        }
        ElMessage.success(res.data.msg);
        loadData();
      }).catch(err => {
        ElMessage.error('网络错误：' + err.message);
      })
    }).catch(() => { })
  } else {
    ElMessage.info("请选择批量数据");
  }

}


const updataK4 = (row) => {
  updataK4DialogRef.value.show(row.id, '上传k4 ', row);
}
const onUpdataBin = (row) => {
  updataBinDialogRef.value.show(row.id, '上传bin ', row);
}
// 点击行内编辑按钮
const onDetailRow = (row) => {
  detailDialogRef.value.show('详情 ', row);
}

const upgradeK4 = (row) => {
  ElMessageBox.confirm("是否升级 " + row.floor + row.name + " K4", '提示').then(() => {
    EsAjax.post(ApiUrls.updateK4, { id: row.id, }).then(res => {
      console.log(res)
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      ElMessage.success("开始升级" + row.floor + row.name + " K4");
      loadData();
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  }).catch(() => { })
}


const upgradeBin = (row) => {
  ElMessageBox.confirm("是否升级 " + row.floor + row.name + " bin", '提示').then(() => {
    EsAjax.post(ApiUrls.updateBin, { id: row.id, }).then(res => {
      if (res.data.code != 200) {
        ElMessage.warning(res.data.data + res.data.msg);
        return;
      }
      ElMessage.success("开始升级" + row.floor + row.name + " bin");
      loadData();
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  }).catch(() => { })



}






// ======================================================
//                      处理事件
// ======================================================

// 处理分页尺寸
const handleChange = (data = null) => {
  queryParam.value.page = data?.page;
  queryParam.value.limit = data?.limit;
  loadData();
}

// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  let _queryParam = queryParam.value
  _queryParam.query = ''
  if (queryForm.value.buildingId) {
    _queryParam.query = "buildingId=" + queryForm.value.buildingId;
  }
  if (queryForm.value.floorId) {
    _queryParam.query += ",floorId=" + queryForm.value.floorId;
  }
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true

  EsAjax.post(ApiUrls.roomDatagrid, { ..._queryParam }).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    dataOfTable.value = list;
    paginationRef.value?.changeTotal({ totalCount: totalCount })
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loading.value = false
  })
}

// 加载楼层数据
const floorFetch = (e) => {
  floorStore.getFloorList(e)
}
//加载大楼数据
buildingStore.getBuildList()
loadData();
</script>
  
